package org.advanced.socket;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;

/**
 * @author John.zhang
 * @version Id: ServerSocketThread, v 1.0 2020/12/14 16:49 ZhiYong Exp $
 * 基于多线程的BIO层面的优化
 */
public class ServerSocketThread implements Runnable {

    Socket socket;

    public ServerSocketThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        System.out.println("客户端" + socket.getPort() + "已经连接");
        try {
            //socket.getInputStream()这里来自于网络的IO ，相当于来自磁盘的new FileInputStream("")
            //IO阻塞
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String line = bufferedReader.readLine();
            System.out.println("收到客户端信息" + line);
            Thread.sleep(5000);
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            bufferedWriter.write("我已经收到了消息\n");

            bufferedWriter.flush();
            bufferedWriter.close();
            bufferedReader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
